<template>
  <div class="login-container">
    <div class="login-view-form">
      <h1>{{ $t("ui.login.title") }}</h1>
      <div class="tabs-container">
        <a-tabs v-model:activeKey="loginType" :change="handleLoginTypeChange">
          <a-tab-pane key="account" :tab="$t('ui.login.accountLogin')" />
          <a-tab-pane key="phone" :tab="$t('ui.login.phoneLogin')" />
        </a-tabs>
      </div>
      <a-form @submit.prevent="handleSubmit">
        <a-form-item
          v-if="loginType === 'account'"
          :validateStatus="errorMessage ? 'error' : undefined"
          :help="errorMessage ? errorMessage : ''"
        >
          <a-input
            v-model:value="username"
            :placeholder="$t('ui.login.username')"
          >
            <template #prefix>
              <user-outlined />
            </template>
            <template #suffix>
              <a-tooltip :title="$t('ui.login.clear')">
                <close-outlined
                  class="pointer-icon"
                  @click="clearUsername"
                  style="color: rgba(0, 0, 0, 0.45)"
                />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item
          v-if="loginType === 'account'"
          :validateStatus="errorMessage ? 'error' : undefined"
          :help="errorMessage ? errorMessage : ''"
        >
          <a-input
            v-model:value="password"
            :type="showPassword ? 'text' : 'password'"
            :placeholder="$t('ui.login.password')"
            required
          >
            <template #prefix>
              <lock-outlined />
            </template>
            <template #suffix>
              <a-tooltip
                :title="
                  showPassword
                    ? $t('ui.login.hidePassword')
                    : $t('ui.login.showPassword')
                "
              >
                <span @click="toggleShowPassword" class="pointer-icon">
                  <eye-invisible-outlined v-if="!showPassword" />
                  <eye-outlined v-else />
                </span>
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          v-if="loginType === 'phone'"
          :validateStatus="errorMessage ? 'error' : undefined"
          :help="errorMessage ? errorMessage : ''"
        >
          <a-input
            v-model:value="phone"
            :placeholder="$t('ui.login.phonePlaceholder')"
          >
            <template #prefix>
              <mobile-outlined />
            </template>
            <template #suffix>
              <a-tooltip :title="$t('ui.login.clear')">
                <close-outlined
                  class="pointer-icon"
                  @click="clearPhone"
                  style="color: rgba(0, 0, 0, 0.45)"
                />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          v-if="loginType === 'phone'"
          :validateStatus="errorMessage ? 'error' : undefined"
          :help="errorMessage ? errorMessage : ''"
        >
          <div class="verification-container">
            <a-input
              v-model:value="verificationCode"
              :placeholder="$t('ui.login.verificationCode')"
              style="flex: 1"
            >
              <template #prefix>
                <lock-outlined />
              </template>
            </a-input>
            <a-button
              @click="getVerificationCode"
              style="margin-left: 8px; flex-shrink: 0"
              >{{ $t("ui.login.getCode") }}</a-button
            >
          </div>
        </a-form-item>

        <a-form-item>
          <div class="flex-container">
            <a-checkbox v-model:checked="autoLogin">{{
              $t("ui.login.autoLogin")
            }}</a-checkbox>
            <a-button
              type="link"
              @click="forgotPassword"
              class="forgot-password"
              >{{ $t("ui.login.forgotPassword") }}</a-button
            >
          </div>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSubmit" style="width: 100%">
            {{ $t("ui.login.login") }}
          </a-button>
        </a-form-item>

        <a-form-item>
          <a-button type="link" @click="register" style="float: right">
            {{ $t("ui.login.register") }}
          </a-button>
        </a-form-item>

        <a-form-item v-if="errorMessage">
          <p class="error-message">{{ errorMessage }}</p>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts">
// import axios from "axios";
import { defineComponent, ref, nextTick, onMounted } from "vue";
import { useStore } from "vuex"; // 导入 Vuex 的 useStore
import { useRouter } from "vue-router"; // 导入 useRouter
import { Form, Input, Button, Checkbox, Tabs, Tooltip } from "ant-design-vue"; // 引入 Ant Design Vue 相关组件
import {
  UserOutlined,
  MobileOutlined,
  CloseOutlined,
  LockOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
} from "@ant-design/icons-vue"; // 导入图标
import { loginUser } from "@/modules/users"; // 引入 loginUser 函数

export default defineComponent({
  name: "LoginView",
  components: {
    "a-form": Form, // 注册 Ant Design Vue 的 Form 组件
    "a-form-item": Form.Item, // 注册 Form.Item 组件
    "a-input": Input, // 注册 Input 组件
    "a-button": Button, // 注册 Button 组件
    "a-checkbox": Checkbox, // 注册 Checkbox 组件
    "a-tabs": Tabs,
    "a-tab-pane": Tabs.TabPane,
    "a-tooltip": Tooltip,
    UserOutlined, // 注册用户图标
    MobileOutlined,
    CloseOutlined, // 注册信息图标
    LockOutlined,
    EyeOutlined,
    EyeInvisibleOutlined,
  },
  setup() {
    const store = useStore(); // 使用 Vuex store
    const username = ref("");
    const password = ref("");
    const phone = ref("");
    const verificationCode = ref("");
    const errorMessage = ref("");
    const showPassword = ref(false); // 用于控制密码的显示和隐藏
    const autoLogin = ref(false); // 自动登录状态
    const loginType = ref("account"); // 默认登录方式为账号密码登录
    const router = useRouter(); // 获取路由实例

    const handleSubmit = async () => {
      console.log("Auto Login:", autoLogin.value); // 打印 autoLogin 的值
      try {
        console.log("登录成功事件");
        const userData = {
          username: username.value,
          password: password.value,
          loginType: loginType.value,
          autoLogin: autoLogin.value,
          phone: phone.value,
          verificationCode: verificationCode.value,
        }; // 示例用户数据
        // 调用 loginUser 函数进行登录
        const response = await loginUser(userData);
        if (response && response.data && response.data.accessToken) {
          // 登录成功后处理
          console.log(`登录成功: ${response.data.accessToken}`);
          if (!autoLogin.value) {
            localStorage.removeItem("userData"); // 清除本地存储中的 userData
          }
          // await store.dispatch("users/login", response.data); // 将用户数据存入 Vuex
          await nextTick();
          router.push("/home"); // 登录成功后跳转到 Home 页面
        } else {
          errorMessage.value = response.message || "登录失败，请重试";
        }
      } catch (error) {
        errorMessage.value = "登录失败，请重试";
      }
    };

    const clearUsername = () => {
      username.value = ""; // 清空用户名输入框
    };

    const clearPhone = () => {
      phone.value = ""; // 清空用户名输入框
    };

    const toggleShowPassword = () => {
      showPassword.value = !showPassword.value; // 切换密码显示状态
    };

    const forgotPassword = () => {
      router.push("/forgot-password"); // 跳转到忘记密码页面
      store.commit("users/setIsForgotPassword", true); // 触发 Vuex mutation
      // 在这里处理忘记密码的逻辑，例如跳转到忘记密码页面
      console.log("忘记密码?");
    };

    const register = () => {
      // 设置 isRegistering 为 true 以显示注册页面
      store.commit("users/setIsRegistering", true); // 触发 Vuex mutation
      // router.push("/home"); // 登录成功后跳转到 Home 页面
      router.push("/register"); // 登录成功后跳转到 Home 页面
      // 在这里处理注册的逻辑，例如跳转到注册页面
      console.log("账号注册");
    };

    const getVerificationCode = async () => {
      // 调用获取验证码的逻辑
      console.log("获取验证码:", phone.value);
      // 可以在这里添加逻辑发送验证码到手机
    };

    const handleLoginTypeChange = (key: string) => {
      loginType.value = key;
      // 清空输入框的内容
      // username.value = '';
      // password.value = '';
      // phone.value = '';
      verificationCode.value = "";
      errorMessage.value = "";
    };

    onMounted(() => {
      const _userDataStr = localStorage.getItem("userdata");
      if (_userDataStr && _userDataStr !== "undefined") {
        const _userData = JSON.parse(_userDataStr);
        if (_userData && _userData.autoLogin) {
          // 如果本地存储有用户数据，则自动登录
          username.value = _userData.username;
          password.value = _userData.password;
          phone.value = _userData.phone;
          autoLogin.value = true;
          console.log("记住用户：写入");
          // await store.dispatch("users/login", userData); // 将用户数据存入 Vuex
          // router.push("/home"); // 登录成功后跳转到 Home 页面
        }
      }
    });

    return {
      username,
      password,
      phone,
      verificationCode,
      errorMessage,
      handleSubmit,
      clearUsername,
      clearPhone,
      showPassword,
      toggleShowPassword, // 返回切换密码显示的方法
      autoLogin,
      forgotPassword, // 返回忘记密码的方法
      register, // 返回注册的方法
      getVerificationCode,
      loginType,
      handleLoginTypeChange,
    };
  },
});
</script>

<style scoped>
.error-message {
  color: red;
}
.login-container {
  display: flex; /* 使用 Flexbox */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin: 10vh;
  background-color: var(--bg-color);
  color: var(--info-color);
}

.login-view-form {
  width: 280px;
  /* background: white; 可选：表单背景颜色 */
  padding: 20px; /* 可选：内边距 */
  border-radius: 8px; /* 可选：圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 可选：阴影效果 */
}

.tabs-container {
  display: flex; /* 使用 Flexbox */
  justify-content: center; /* 水平居中 */
  /* margin-bottom: 16px; 添加底部间距 */
}

.flex-container {
  display: flex; /* 使用 Flexbox */
  justify-content: space-between; /* 使子项左右分离 */
  align-items: center; /* 垂直居中对齐 */
}

.verification-container {
  display: flex; /* 使用 Flexbox */
  width: 100%; /* 容器宽度为 100% */
}

.verification-container .ant-input {
  margin-right: 8px; /* 输入框和按钮之间的间距 */
}
/* 鼠标悬停时变为指针形状 */
.pointer-icon {
  cursor: pointer; /* 设置光标为 pointer */
}
</style>
